package com.mathlearning.auth.specification;

import com.mathlearning.auth.entity.Discussion;
import com.mathlearning.auth.entity.DiscussionTag;
import jakarta.persistence.criteria.*;
import org.springframework.data.jpa.domain.Specification;

/**
 * 讨论查询条件构建器
 */
public class DiscussionSpecification {

    /**
     * 未删除的讨论
     */
    public static Specification<Discussion> isNotDeleted() {
        return (root, query, cb) -> cb.equal(root.get("isDeleted"), 0);
    }

    /**
     * 关键词搜索（标题或内容）
     */
    public static Specification<Discussion> keywordLike(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return null;
        }
        
        return (root, query, cb) -> {
            String pattern = "%" + keyword.trim() + "%";
            Predicate titleLike = cb.like(root.get("title"), pattern);
            Predicate contentLike = cb.like(root.get("content"), pattern);
            return cb.or(titleLike, contentLike);
        };
    }

    /**
     * 标签筛选
     */
    public static Specification<Discussion> hasTag(String tag) {
        if (tag == null || tag.trim().isEmpty()) {
            return null;
        }
        
        return (root, query, cb) -> {
            // 需要去重，避免多个标签导致重复结果
            query.distinct(true);
            
            // 使用子查询：讨论ID在指定标签的讨论ID列表中
            Subquery<Long> subquery = query.subquery(Long.class);
            Root<DiscussionTag> tagRoot = subquery.from(DiscussionTag.class);
            subquery.select(tagRoot.get("discussionId"))
                    .where(cb.equal(tagRoot.get("tagName"), tag.trim()));
            
            return root.get("id").in(subquery);
        };
    }

    /**
     * 按热度排序（点赞+评论+收藏）
     */
    public static Specification<Discussion> orderByHot() {
        return (root, query, cb) -> {
            // 计算热度：likes + comments + favorites
            Expression<Integer> hotScore = cb.sum(
                cb.sum(root.get("likes"), root.get("comments")),
                root.get("favorites")
            );
            query.orderBy(cb.desc(hotScore));
            return null;
        };
    }

    /**
     * 按最新排序
     */
    public static Specification<Discussion> orderByLatest() {
        return (root, query, cb) -> {
            query.orderBy(cb.desc(root.get("createdAt")));
            return null;
        };
    }

    /**
     * 按未回答排序（评论数升序）
     */
    public static Specification<Discussion> orderByUnanswered() {
        return (root, query, cb) -> {
            query.orderBy(
                cb.asc(root.get("comments")),
                cb.desc(root.get("createdAt"))
            );
            return null;
        };
    }
}

